<template>
  <el-card>
    <el-form inline>
      <el-form-item>
        <el-input placeholder="用户名" v-model="username"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getUserList">查询</el-button>
        <el-button @click="reset">清空</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="showSaveUser">添加</el-button>
    <el-button type="danger">批量删除</el-button>

    <el-table :data="userList" border class="user-table">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="55" align="center" label="序号" />
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="用户昵称" prop="nickName" />
      <el-table-column label="角色列表" prop="roleName" />
      <el-table-column label="创建时间" prop="gmtCreate" />
      <el-table-column label="更新时间" prop="gmtModified" />
      <el-table-column label="操作" width="200" fixed="right">
        <template v-slot="{ row }">
          <el-tooltip content="分配角色" placement="top" effect="light">
            <el-button type="primary" :icon="UserFilled" size="small" @click="showAssignRole(row.id, row.username)" />
          </el-tooltip>
          <el-tooltip content="修改用户" placement="top" effect="light">
            <el-button type="warning" :icon="Edit" size="small" />
          </el-tooltip>
          <el-tooltip content="删除用户" placement="top" effect="light">
            <el-button type="danger" :icon="Delete" size="small" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="prev, pager, next, jumper,  sizes, total,"
      :total="total"
      small
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </el-card>
  <el-dialog v-model="visible" title="添加用户">
    <el-form label-width="100px" :model="userFormData" :rules="rules" ref="userFormRef">
      <el-form-item label="用户名" prop="username">
        <el-input placeholder="用户名" v-model="userFormData.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称">
        <el-input placeholder="用户昵称" v-model="userFormData.nickName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input placeholder="密码" type="password" v-model="userFormData.password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="saveUser">确定</el-button>
        <el-button @click="visible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="assignRoleVisible" title="分配用户角色">
    <el-form label-width="100px">
      <el-form-item label="用户名"> {{ selectedUser.username }} </el-form-item>
      <el-form-item label="角色列表">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange($event as boolean)">全选</el-checkbox>
        <el-checkbox-group v-model="assignRoleList" @change="handleCheckedCitiesChange">
          <!-- label代表选中的值 -->
          <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="assignUser">确定</el-button>
        <el-button @click="assignRoleVisible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: "XUser",
};
</script>

<script lang="ts" setup>
import {ref,onMounted,reactive} from "vue"
import { Search, UserFilled, Edit, Delete } from "@element-plus/icons-vue";
import { getUserListApi, saveUserApi, getUserRoleApi, assignUserRoleApi } from "@/api/acl/user";
import type { UserList, RoleList } from "@/api/acl/model/userModel";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
const userList = ref<UserList>([]);
    const username = ref("");
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(1);
const visible = ref(false);

const userFormData = reactive({
  username: "",
  nickName: "",
  password: "",
});
// 
const rules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入用户密码", trigger: "blur" }],
});
// 获取用户列表
const getUserList = async () => {
  const result = await getUserListApi({
    page: currentPage.value,
    limit: pageSize.value,
    username: username.value,
  });
  userList.value = result.items;
  total.value = result.total;
};
const userFormRef = ref<FormInstance>();
// 显示添加用户
const showSaveUser = () => {
  userFormRef.value?.clearValidate();
  userFormData.username = "";
  userFormData.nickName = "";
  userFormData.password = "";
  visible.value = true;
}
// 添加用户
const saveUser = async () => {
  await saveUserApi(userFormData);
  ElMessage.success("添加用户成功");
  visible.value = false;
  getUserList();
};
// 清空
const reset = () => {
  username.value = "";
  getUserList();
}
// 一上来请求数据
onMounted(getUserList);
// 点击分页请求分页列表
const handleCurrentChange = (newCurrentPage: number) => {
  currentPage.value = newCurrentPage;
  getUserList();
};
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  getUserList();
};
// 分配用户角色
const assignRoleVisible = ref(false);
const checkAll = ref(false);
const isIndeterminate = ref(true);
// 所有角色列表
const roleList = ref<RoleList>([]);
// 用户选中的角色列表
const assignRoleList = ref<number[]>([]);
// 选中用户的名字
const selectedUser = ref({
  id: 0,
  username: "",
});

const showAssignRole = async (id: number, username: string) => {
  // 发送请求，请求当前用户角色数据
  const result = await getUserRoleApi(id);

  selectedUser.value = {
    id,
    username,
  };
  assignRoleVisible.value = true;

  // 所有角色列表
  roleList.value = result.allRolesList;
  // 请求回来的数据[]里面是对象，而我们需要的是id，格式化
  assignRoleList.value = result.assignRoles.map((role) => role.id);

  // 半选状态
  isIndeterminate.value = assignRoleList.value.length === roleList.value.length || assignRoleList.value.length === 0 ? false : true;
  // 全选状态
  checkAll.value = assignRoleList.value.length === roleList.value.length;
};

// 全选&全不选
const handleCheckAllChange = (val: boolean) => {
  isIndeterminate.value = false;
  if (val) {
    // 全选
    assignRoleList.value = roleList.value.map((role) => role.id);
    return;
  }
  // 全不选
  assignRoleList.value = [];
};
// 单个复选框触发
const handleCheckedCitiesChange = () => {
  if (assignRoleList.value.length === roleList.value.length || assignRoleList.value.length === 0) {
    isIndeterminate.value = false;
  } else {
    isIndeterminate.value = true;
  }
};

const assignUser = async () => {
  await assignUserRoleApi(selectedUser.value.id, assignRoleList.value);
  assignRoleVisible.value = false;
  ElMessage.success("分配用户角色成功");
  getUserList();
};

</script>

<style scoped>
    .user-table {
      margin: 10px 0;
    }
   
    </style>
    <style>
         .el-pagination__total{
        position: absolute;
        right: 35px;
        margin-left: 10px;
    }
    </style>
    